import React, {Component} from 'react'
import DefaultLayout from '../../layouts/default_layout'
import {NavBar, Icon} from 'antd-mobile'
import {withRouter} from 'react-router-dom'
import CInput from '../../components/c_input'
import {createForm} from 'rc-form'
import {Button} from 'antd-mobile'
import {connect} from 'react-redux'
import Loading from '../../components/loading'
import './chat_box.scss'
import {post, moment, queryParse} from '../../common/js/utils'

function mapStateToProps(state, props) {
  return {
    userInfo: state.userInfo
  }
}

function format(time) {
  const now = moment(new Date()).format('YYYY-MM-DD')
  if (now === moment(time).format('YYYY-MM-DD')) {
    return moment(time).format('HH:mm:ss')
  } else {
    return moment(time).format('YYYY-MM-DD HH:mm:ss')
  }
}

@withRouter
@createForm()
@connect(mapStateToProps)
class ChatBox extends Component {

  skip = 0
  size = 20
  total = null

  state = {
    list: [],
    toUser: {},
    loading: false
  }

  onScroll = (e) => {
    const scrollTop = e.target.scrollTop
    const {loading, list} = this.state
    if (scrollTop < 5 && (this.total === null || this.total > list.length)) {
      if (!loading) {
        this.skip = list.length
        this.getList()
      }
    }
  }

  doSend = () => {
    const {getFieldValue, setFieldsValue} = this.props.form
    const {location} = this.props
    const query = queryParse(location.search)
    const content = getFieldValue('message').trim()
    if (!content) return
    window.chatWebSocket.emit('send message', query.userId, content)
    const list = this.state.list.slice(0)
    list.push({
      content,
      belongsTo: this.props.userInfo._id,
      meta: {
        createdAt: new Date().getTime()
      }
    })
    this.setState({list}, this.scrollToBottom)
    setFieldsValue({ message: '' })
  }

  onKeyDown = (e) => {
    if (e.keyCode === 13) {
      this.doSend()
    }
  }

  getToUser = () => {
    const {location} = this.props
    const query = queryParse(location.search)
    post('/users/getUser', {
      id: query.userId
    }).then(res => {
      this.setState({
        toUser: res.data
      }, this.scrollToBottom)
    })
  }

  getList = () => {
    const {location} = this.props
    const query = queryParse(location.search)
    let list = this.state.list.slice(0)
    if (this.skip === 0) list = []
    post('/socket/messages', {
      id: query.userId,
      dialogId: query.dialogId,
      skip: this.skip,
      size: this.size
    }, loading => { this.setState({loading}) }).then(res => {
      res.data.reverse()
      this.setState({
        list: res.data.concat(list)
      }, () => {
        if (this.skip === 0) {
          this.scrollToBottom()
        }
      })
      this.total = res.total
    })
  }

  scrollToBottom = () => {
    const dom = this.refs.scrollView
    const con = this.refs.scrollContent
    if (dom && con) {
      dom.scrollTop = con.clientHeight
    }
  }

  onReceive = (message) => {
    const list = this.state.list.slice(0)
    list.push(message)
    this.setState({list}, this.scrollToBottom)
    window.chatWebSocket && window.chatWebSocket.emit('sign single message', message._id)
  }

  componentWillMount() {
    const {location} = this.props
    const query = queryParse(location.search)
    window.receiveMessage = this.onReceive
    this.getList()
    if (query.userId) {
      this.getToUser()
    }
  }
  componentWillUnmount() {
    window.receiveMessage = null
  }

  render() {
    const {history, userInfo, className} = this.props
    const {list, toUser, loading} = this.state
    if (!toUser._id) return (<Loading className={className} />)
    return (
      <DefaultLayout
        header={
          <NavBar
            mode="light"
            icon={<Icon type="left" />}
            onLeftClick={() => {
              history.go(-1)
            }}
          >{toUser.nickname}</NavBar>
        }
        footer={
          <div
            className="flex-row align-center chat-box-footer"
          >
            <CInput
              form={this.props.form}
              name={'message'}
              placeholder={'请输入需要发送的消息'}
              className={'input'}
              onKeyDown={this.onKeyDown}
            />
            <div className={'btn'}>
              <Button
                onClick={this.doSend}
                type={'primary'}
                size={'small'}
              >发送</Button>
            </div>
          </div>
        }
        className={className}
      >
        <div
          onScroll={this.onScroll}
          className="chat-list scroll-view"
          ref="scrollView"
        >
          {
            loading
              ? <Loading />
              : null
          }
          <div ref="scrollContent">
            {
              list.map((item, key) => (
                <div className={userInfo._id === item.belongsTo ? 'right' : 'left'} key={key} >
                  <div className="time">{format(item.meta.createdAt)}</div>
                  <div className={'content'}>{item.content}</div>
                  <div className={'avatar'}>
                    <img src={
                      userInfo._id === item.belongsTo
                        ? userInfo.avatar
                        : toUser.avatar
                    } alt="用户头像"/>
                  </div>
                </div>
              ))
            }
          </div>
        </div>
      </DefaultLayout>
    )
  }
}

export default ChatBox
